<template>
    <div id="productDetail">
        <!-- 顶部导航栏 -->
        <van-nav-bar @click-left="onClickLeft" :title="product.name" left-text="返回" left-arrow>
            <template #right>
                <van-icon @click="showShare = !showShare" name="ellipsis" size="18" />
            </template >
        </van-nav-bar>
        <!-- 轮播图 -->
        <van-swipe :autoplay="3000" lazy-render>
            <van-swipe-item >
                <img height="250px" width="100%" :src="product.thumbs_text" />
            </van-swipe-item>
        </van-swipe>
        <!-- 商品介绍 -->
        <div class="detailbox">
            <h4>{{product.name}}</h4>
            <div class="price"><em>￥</em>{{ product.price }}
                <b>库存{{ product.stock }}</b>
            </div>
        </div>
        <!-- 标签切换 -->
        <van-tabs color="#ee0a24" v-model:active="active" type="card">
            <van-tab title="产品参数" name="a">
                <div class="productInfo" v-html="product.content"></div>
            </van-tab>
            <van-tab title="用户评论" name="b">
                <div class="productInfo" v-if="rate">
                    <div class="totalRate">
                        <div class="leftRate">
                            <p class="leftRateTitle">商品评分</p>
                            <p class="rate">{{rate}}</p>
                        </div>
                        <div class="rightBox">
                            <van-rate v-model="rate" readonly allow-half />
                        </div>
                    </div>
                    <div class="itemD" v-for="item in commentList" :key="item.id">
                        <div class="topBoxD">
                            <div class="avatarD">
                                <img :src="item.business.avatar_text" alt="">
                            </div>
                            <div class="userInfoD">
                                <p>{{item.business.nickname}}</p>
                            </div>
                            <div class="timeD">
                                <p>{{item.updatetime_text}}</p>
                            </div>
                        </div>
                        <div class="contentD">
                            <div class="textD">
                                {{item.comment}}
                            </div>
                            <van-field>
                                <template #input>
                                    <van-uploader :show-upload="false" :deletable=false readonly v-model="item.proimg_text" multiple />
                                </template>
                        </van-field>
                        </div>
                    </div>
                </div>
                <div class="productInfo" v-else>
                    <div class="nocomment">
                        <p>暂时没有评论</p>
                    </div>
                </div>
            </van-tab>
        </van-tabs>
        <!-- 分享面板 -->
        <van-share-sheet
        v-model:show="showShare"
        title="立即分享给好友"
        :options="options"
        />
        <!-- 购物车导航 -->
        <van-action-bar>
            <van-action-bar-icon icon="chat-o" text="客服" @click="customer"/>
            <van-action-bar-icon to="/cart/index" icon="cart-o" text="购物车" ref="cart" :badge="cartNum" />
            <van-action-bar-button type="warning" text="加入购物车" @click="addCart"/>
            <van-action-bar-button type="danger" text="立即购买" @click="buy"/>
        </van-action-bar>
    </div>
</template>

<script setup>
import { getCurrentInstance, onBeforeMount, onMounted, reactive, ref } from "vue";
    // 返回
    const onClickLeft = () => history.back();
    // 评分
    const rate = ref(0);

    // 标签切换
    const active = ref('a');

    // 分享面板数据
    const showShare = ref(false);
    const options = [
      [
        { name: '微信', icon: 'wechat' },
        { name: '朋友圈', icon: 'wechat-moments' },
        { name: '微博', icon: 'weibo' },
        { name: 'QQ', icon: 'qq' },
      ],
      [
        { name: '复制链接', icon: 'link' },
        { name: '分享海报', icon: 'poster' },
        { name: '二维码', icon: 'qrcode' },
        { name: '小程序码', icon: 'weapp-qrcode' },
      ],
    ];

    onBeforeMount(()=>{
        getData()
        getCartData()
        getComment()
    })

    const {proxy} = getCurrentInstance();
    let product = ref({})
    const proid = proxy.$route.query.proid?parseInt(proxy.$route.query.proid):0;
    // 发送请求，获取商品信息
    const getData = async () => {
        let data = {
            proid
        }
        let result = await proxy.$POST({
            url:"/product/detail",
            params:data
        })
        if(result.code){
            product.value = result.data
            return false
        }else{
            proxy.$fail(result.msg)
            return false
        }
    }

    const userInfo = proxy.$cookies.get("business")?proxy.$cookies.get("business"):{}
    //发送请求 ，获取购物车信息
    let cartNum = ref(0);
    const getCartData = async () => {
        // 判断是否登录
        if(!userInfo){
            return false
        }
        let data = {
            busid:userInfo.id?userInfo.id:0
        }
        let result = await proxy.$POST({
            url:"/product/cart",
            params:data
        })
        if(result.code){
            cartNum.value = result.data
            return false
        }else{
            proxy.$fail(result.msg)
            return false
        }
    }

    // 获得商品评论信息
    const commentList = ref({});
    const getComment = async () =>{
        let result = await proxy.$POST({
            url:"/product/comment",
            params:{proid}
        })
        if(result.code){
            commentList.value = result.data
            let totalRate = 0
            result.data.forEach(item=>{
                totalRate +=  parseFloat(item.rate) 
            })
            rate.value = parseFloat((totalRate/result.data.length).toFixed(1))
            return false
        }else{
            proxy.$fail(result.msg);
            return false
        }
    }

    // 加入购物车
    const addCart = async () => {
        // 判断是否登录
        if(!userInfo){
            proxy.$fail("请先登录");
            return false
        }
        let data = {
            busid:userInfo.id,
            proid
        }
        let result = await proxy.$POST({
            url:"/product/addCart",
            params:data
        })
        if(result.code){
            getCartData()
            proxy.$success({
                message:result.msg,
                duration:1000,
                onClose:()=>{
                    proxy.$dialog({
                        title:"提醒",
                        message:"前往购物车",
                    })
                    .then(()=>{
                        proxy.$router.push("/cart/index")
                        return false
                    })
                    .catch(()=>{
                        return false
                    })
                }
            })
           
        }else{
            proxy.$fail(result.msg)
            return false
        }
    }

    // 客服
    const customer = async () => {
        if(!userInfo){  
            proxy.$fail("请先登录")
            return false
        }else{
            proxy.$router.push("/product/customer")
            return false
        }        
    }

    // 立即购买
    const buy = async () => {
        proxy.$dialog({
            title:"提醒",
            message:"确定要购买吗?"
        }).then(()=>{
            if(product.value.stock == 0){
                proxy.$fail("商品库存不足");
                return false
            }
            proxy.$router.push({
                path:"/cart/getOrder",
                query:{
                    proid,
                    total:product.value.price*100
                }
            })
        })
        

    }
</script>

<style>
    #productDetail .van-share-sheet__options{
        justify-content: space-around;
    }
    #productDetail .van-tabs__nav--card{
        margin: 0;
    }

    .productInfo{
        margin-bottom: 50px;
        padding: 0 10px;
    }

    .productInfo .itemD{
        padding-top: .625rem;
        border-top: 1px solid #666666;
    }

    .productInfo .itemD .topBoxD{
        display: flex;
        align-items: center;
    }
    .productInfo .itemD .topBoxD .avatarD{
        width:2.5rem;
        height: 2.5rem;
        overflow: hidden;
        border-radius: 50%;
    }

    .userInfoD p{
        font-size: 1rem;
        margin-left: 5px;
    }

    .timeD{
        flex: 1;
        text-align: right;
    }

    .timeD p{
        font-size: .9rem;
    }

    .contentD {
        padding: 1rem;
        font-size: 1rem;
    }

    #productDetail .van-cell{
        padding: 0;
    }

    .productInfo .totalRate{
        display: flex;
        align-items: center;
    }

    .productInfo .totalRate .leftRate{
        text-align: center;        
        margin: 1rem;
        padding-right: 1rem;
        border-right: 1px solid #666666;
    }

    .productInfo .totalRate .rightBox{
        flex: 1;
        display: flex;
        justify-content: center;
    }

    .productInfo .totalRate .leftRate .leftRateTitle{
        font-size: 1rem;
    }

    .productInfo .totalRate .leftRate .rate{
        font-size: 2rem;
        font-weight: 700;
        color: red;
    }

    .productInfo .nocomment {
        margin-top: 10px;
        text-align: center;
        font-size: 1rem;
    }

</style>